package com.ego.trade.service.impl;

import com.ego.commons.constant.Constant;
import com.ego.commons.pojo.CartPojo;
import com.ego.commons.pojo.EgoResult;
import com.ego.commons.pojo.OrderPojo;
import com.ego.commons.pojo.ShopCart;
import com.ego.commons.utils.ServletUtil;
import com.ego.dubbo.service.TbOrderDubboService;
import com.ego.pojo.TbOrder;
import com.ego.pojo.TbOrderItem;
import com.ego.pojo.TbUser;
import com.ego.rabbitmq.send.PublishMessage;
import com.ego.trade.service.TradeService;
import org.apache.catalina.User;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TradeServiceImpl implements TradeService {


    @Autowired
    private PublishMessage publishMessage;

    @Value("${ego.operation.exchange}")
    private String exchange;

    @Value("${ego.trade.insertOrderRoutingKey}")
    private String insertOrderRoutingKey;


    @Value("${ego.trade.sendMailRoutingKey}")
    private String sendMailRoutingKey;




    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public EgoResult insertOrder(OrderPojo orderPojo) {



        //发送同步消息,完成新增订单功能 ；返回的是订单ID
        String result = (String)publishMessage.syncSenderMessage(exchange, insertOrderRoutingKey, orderPojo);
        // 0 ：异常 1：库存不出 ，订单id：成功
        System.out.println("mq执行返回结果 = " + result);
        if(result.equals("0")){
            return EgoResult.error("程序出现异常，新增订单失败");
        }else if(result.equals("1")){
            return EgoResult.error("亲，手慢了，库存已经不够了");
        }

        //删除购物车中用户购买后的商品
        TbUser loginUser = (TbUser) ServletUtil.getRequest().getSession().getAttribute(Constant.LOGIN_USER_IN_SESSION);
        System.out.println("loginUser = " + loginUser);


        String key = Constant.LOGIN_USER_REDIS_SHOP_CART_KEY_PREFIX+loginUser.getUsername();
        //获取用户的购车
        ShopCart shopCart = (ShopCart) redisTemplate.opsForValue().get(key);
        //获取购物车中的商品

        //循环用户购买的商品集合
        List<TbOrderItem> orderItems = orderPojo.getOrderItems();
        for (TbOrderItem orderItem : orderItems) {
            shopCart.deleteToCart(Long.valueOf(orderItem.getItemId()));
        }

        //重新保存购物车
        redisTemplate.opsForValue().set(key,shopCart);



        //为了不再编写新的pojo，将用户邮箱和订单id拼接成一个字符串传递过去

        String orderIdAndUserEmail = result+":"+loginUser.getEmail();
        //161535846128986:lili@email.com


        //发送异步小消息，发送邮件
        publishMessage.asyncSenderMessage(exchange,sendMailRoutingKey,orderIdAndUserEmail);


        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("orderId",result);
        resultMap.put("payment",orderPojo.getPayment());
        resultMap.put("date",new Date());
        System.out.println("resultMap = " + resultMap);
        return EgoResult.ok(resultMap);
    }
}
